package com.redisson_lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RLockUtil {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 可重入锁
     * @param key
     */
    public void reentranLock(String key){
        RLock rLock = redissonClient.getLock(key);
        rLock.lock();
    }

    /**
     * 指定时间自动解锁
     * @param key
     * @param time
     */
    public void reentranLock(String key,Long time){
        RLock rLock  = redissonClient.getLock(key);
        rLock.lock(time, TimeUnit.SECONDS);
    }

    /**
     * 公平锁
     * @param key
     */
    public void fairLock(String key){
        RLock rLock = redissonClient.getFairLock(key);
        rLock.lock();
    }

    /**
     * 解锁
     * @param key
     */
    public void unReentranLock(String key){
        RLock rLock = redissonClient.getLock(key);
      rLock.unlock();
    }
    public Boolean reentranTryLock(String key){
        RLock rLock = redissonClient.getLock(key);
      return   rLock.tryLock();
    }

    /**
     * 公平解锁
     * @param key
     */
    public void unFailLock(String key){
        RLock rLock = redissonClient.getFairLock(key);
        if(rLock.isHeldByCurrentThread()){
            rLock.unlock();
        }
    }

}
